package com.sgb.kjwl.view.ui.activity.self.logistics;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bigkoo.pickerview.view.OptionsPickerView;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityBiddingCargoPublishMoreBinding;
import com.sgb.kjwl.model.entity.transport.CargoPublishEntity;
import com.sgb.kjwl.model.entity.transport.CompanyInvoiceEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.InvoiceRateEntity;
import com.sgb.kjwl.model.entity.transport.SingleItemEntity;
import com.sgb.kjwl.utils.DefaultUtil;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.utils.PickerHelper;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.view.ui.adapter.CargoInvoiceAdapter;
import com.sgb.kjwl.view.ui.adapter.transport.CargoCustomValueAdapter;
import com.sgb.kjwl.view.widget.InvoicingCompanyPopWindow;
import com.sgb.kjwl.view.widget.transport.AMapDialog;
import com.sgb.kjwl.viewmodel.transport.BiddingCargoPublishMoreViewModel;
import com.sgb.link.entity.AMapAddressEntity;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.util.ArrayUtil;
import com.swgk.core.util.DensityUtils;
import com.swgk.core.util.MToast;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author: 杨畔
 * @date: 2020/12/29 17:50
 * @Description: 竞价货源发布填写更多信息页面
 */
public class BiddingCargoPublishMoreActivity extends AppActivity {
    BiddingCargoPublishMoreViewModel viewModel;
    ActivityBiddingCargoPublishMoreBinding binding;
    //选择弹窗
    private OptionsPickerView<InvoiceRateEntity> mInvoicePicker;
    private OptionsPickerView<GoodsInfoTypeEntity3> mRequirePicker;
    private InvoicingCompanyPopWindow mCompanyPop;
    //自定义字段列表
    private List<SingleItemEntity> mCustomList;
    private CargoCustomValueAdapter mCustomAdapter;
    //开票信息
    private List<SingleItemEntity> mList;
    private CargoInvoiceAdapter mAdapter;
    //数据实体类
    private CargoPublishEntity mEntity;

    public static void start(Activity activity, CargoPublishEntity entity, int requestCode) {
        Intent intent = new Intent(activity, BiddingCargoPublishMoreActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra(RouterKey.DATA, entity);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        viewModel = new ViewModelProvider(this).get(BiddingCargoPublishMoreViewModel.class);
    }

    @Override
    protected void init() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_bidding_cargo_publish_more);
        binding.setLifecycleOwner(this);
        binding.includeTitle.titleView.setText("更多信息");
        initPopup();
        initRecycler();
        initEvent();
        initData();
    }

    private void initPopup() {
        mCompanyPop = new InvoicingCompanyPopWindow(this);
        mCompanyPop.setOnResultClick((key1, key2, key3) -> {
            if (key1 == null) return;
            CompanyInvoiceEntity entity = (CompanyInvoiceEntity) key1;
            //添加属性
            mEntity.setInvoicingCompanyName(entity.getCompanyName());
            mEntity.setInvoicingTaxNumber(entity.getCreditCode());
            mEntity.setInvoicingAddress(entity.getAddress());
            mEntity.setInvoicingCompanyPhone(entity.getPhone());
            mEntity.setInvoicingBank(entity.getBank());
            mEntity.setInvoicingBankAccount(entity.getBankAccount());
            mEntity.setInvoicingBankNumber(entity.getBankNumber());
            //设置公司信息
            syncCompanyInvoice();
        });
    }

    private void initRecycler() {
        //公司开票信息
        mList = new ArrayList<>();
        mAdapter = new CargoInvoiceAdapter(mList);
        binding.rvReleaseCargoInfo.setLayoutManager(new LinearLayoutManager(this));
        DividerDecoration.builder(this)
                .colorRes(R.color.color_line)
                .size(1, TypedValue.COMPLEX_UNIT_PX)
                .insets(DensityUtils.dip2px(getActivity(),14), DensityUtils.dip2px(getActivity(),14))
                .build()
                .addTo(binding.rvReleaseCargoInfo);
        mAdapter.bindToRecyclerView(binding.rvReleaseCargoInfo);
        //自定义字段
        mCustomList = new ArrayList<>();
        mCustomAdapter = new CargoCustomValueAdapter(mCustomList);
        binding.rvReleaseCargoField.setNestedScrollingEnabled(false);
        binding.rvReleaseCargoField.setLayoutManager(new LinearLayoutManager(this));
        DividerDecoration.builder(this)
                .colorRes(R.color.transparent)
                .showFirstDivider()
                .size(10, TypedValue.COMPLEX_UNIT_DIP)
                .build()
                .addTo(binding.rvReleaseCargoField);
        mCustomAdapter.bindToRecyclerView(binding.rvReleaseCargoField);
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initEvent() {
        binding.setOnClick(this);
        binding.includeTitle.ivBack.setOnClickListener(this);
        //自定义字段删除监听
        mCustomAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.iv_release_cargo_del) {
                mCustomList.remove(position);
                mCustomAdapter.notifyDataSetChanged();
            }
        });
        //接口回调
        viewModel.ldInvoiceRateEntity.observe(this, this::syncInvoice);
        viewModel.ldRequire.observe(this, this::syncRequire);
        viewModel.ldCompanyInvoice.observe(this, entity -> mCompanyPop.setData(entity));
    }

    private void initData() {
        mEntity = getIntent().getParcelableExtra(RouterKey.DATA);
        if (mEntity == null) {
            mEntity = new CargoPublishEntity();
        } else {
            syncData();
        }
        //获取页面数据
        viewModel.getInvoices(this);
        viewModel.getRequire();
        viewModel.getInvoiceList(this);
    }

    private void syncData() {
        //设置地址
        if (mEntity.getProjectAddress() != null) {
            binding.tvReleaseCargoProjectAddress.setText(String.format("%s%s%s%s",
                    mEntity.getProjectAddress().getProjectProvinceName(),
                    mEntity.getProjectAddress().getProjectCityName(),
                    mEntity.getProjectAddress().getProjectDistrictName(),
                    mEntity.getProjectAddress().getAddress()));
        }
        //todo 字段待调整
        if (!TextUtils.isEmpty(mEntity.getProjectName())) {
            binding.etReleaseCargoProjectName.setText(mEntity.getProjectName());
        }
        if (!TextUtils.isEmpty(mEntity.getProjectDesc())) {
            binding.etReleaseCargoProjectDesc.setText(mEntity.getProjectDesc());
        }
        if (!TextUtils.isEmpty(mEntity.getTransportReq())) {
            binding.etReleaseCargoTransportReq.setText(mEntity.getTransportReq());
        }
        if (!TextUtils.isEmpty(mEntity.getPartyAAgreement())) {
            binding.etReleaseCargoPartyAAgreement.setText(mEntity.getPartyAAgreement());
        }
        if (!TextUtils.isEmpty(mEntity.getPartyBAgreement())) {
            binding.etReleaseCargoPartyBAgreement.setText(mEntity.getPartyBAgreement());
        }
        if (!TextUtils.isEmpty(mEntity.getBreachOfContract())) {
            binding.etReleaseCargoBreachOfContract.setText(mEntity.getBreachOfContract());
        }
        if (!TextUtils.isEmpty(mEntity.getTerminationAgreement())) {
            binding.etReleaseCargoTerminationAgreement.setText(mEntity.getTerminationAgreement());
        }
        //装车/卸车要求
        binding.tvReleaseCargoRequire.setText(viewModel.getRequireStr(mEntity.getRequire()));
        //发票要求信息
        checkInvoiceInfo();
        //设置公司信息
        if (!TextUtils.isEmpty(mEntity.getInvoicingCompanyName())) {
            syncCompanyInvoice();
        }
        //自定义字段
        if (ArrayUtil.isNotNullAndEmpty(mEntity.getCustomList())) {
            mCustomList.addAll(mEntity.getCustomList());
            mCustomAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 设置发票要求
     */
    private void syncInvoice(List<InvoiceRateEntity> list) {
        if (list == null) return;
        mInvoicePicker = PickerHelper.with(this).getCommonPicker("发票要求", list, (options1, options2, options3, v) -> {
            InvoiceRateEntity entity = list.get(options1);
            //设置数据
            if (!TextUtils.isEmpty(entity.getRate()))
                mEntity.setTariff(Double.parseDouble(entity.getRate()));
            if (!TextUtils.isEmpty(entity.getNo()))
                mEntity.setInvoiceNo(entity.getNo());
            if (!TextUtils.isEmpty(entity.getInvoiceRequest()))
                mEntity.setInvoice(entity.getInvoiceRequest());

            //设置回显
            binding.tvReleaseCargoInvoice.setText(DefaultUtil.getString(entity.getName()));
        });
    }

    /**
     * 发票要求信息匹配检测
     */
    private void checkInvoiceInfo() {
        if (mEntity.isInvoiceChanges()) {
            mEntity.setInvoiceNo("");
            mEntity.setInvoice("");
            mEntity.setTariff(null);
        } else if (!TextUtils.isEmpty(mEntity.getInvoice()) && mEntity.getTariff() != null && !TextUtils.isEmpty(mEntity.getInvoiceNo())) {
            if (mEntity.getInvoice().equals("不开发票")) {
                binding.tvReleaseCargoInvoice.setText(mEntity.getInvoice());
            } else {
                String invoiceStr = NumberUtil.trim0(mEntity.getTariff()) + "%" + mEntity.getInvoice();
                binding.tvReleaseCargoInvoice.setText(invoiceStr);
            }
        }
    }

    /**
     * 设置公司信息
     */
    private void syncCompanyInvoice() {
        binding.tvReleaseCargoCompany.setText(DefaultUtil.getString(mEntity.getInvoicingCompanyName()));
        mList.clear();
        mList.add(new SingleItemEntity("税号", mEntity.getInvoicingTaxNumber()));
        mList.add(new SingleItemEntity("地址", mEntity.getInvoicingAddress()));
        mList.add(new SingleItemEntity("企业电话", mEntity.getInvoicingCompanyPhone()));
        mList.add(new SingleItemEntity("开户银行", mEntity.getInvoicingBank()));
        mList.add(new SingleItemEntity("银行账号", mEntity.getInvoicingBankAccount()));
        mList.add(new SingleItemEntity("开户行行号", mEntity.getInvoicingBankNumber()));
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 设置装卸要求
     */
    private void syncRequire(List<GoodsInfoTypeEntity3> list) {
        mRequirePicker = PickerHelper.with(this).getCommonPicker("选择装车要求", list, (options1, options2, options3, v) -> {
            GoodsInfoTypeEntity3 entity = list.get(options1);
            //设置数据
            mEntity.setRequire(NumberUtil.convertToInt(entity.getNo()));
            //设置回显
            binding.tvReleaseCargoRequire.setText(DefaultUtil.getString(entity.getName()));
        });
    }

    @Override
    public void onClick(View v) {
        closeKeybord();
        if (v == binding.includeTitle.ivBack) {
            finish();
        } else if (v == binding.llReleaseCargoProjectAddress) {
            AMapDialog.launch(this);
        } else if (v == binding.llReleaseCargoRequire) {
            if (mRequirePicker != null) {
                mRequirePicker.show();
            }
        } else if (v == binding.llReleaseCargoInvoice) {
            if (mInvoicePicker != null) {
                mInvoicePicker.show();
            }
        } else if (v == binding.llReleaseCargoCompany) {
            mCompanyPop.showDownPopwindow(binding.tvReleaseCargoSubmit, true);
            mCompanyPop.backgroundAlpha(0.5f);
        } else if (v == binding.tvReleaseCargoAdd) {
            //添加更多字段
            addField();
        } else if (v == binding.tvReleaseCargoSubmit) {
            clearAllFocus();
            checkData();
        }
    }

    /**
     * 添加更多字段
     */
    private void addField() {
        if (mCustomList.size() >= 3) {
            MToast.showToast(this, "最多添加3个字段");
            return;
        }
        mCustomList.add(new SingleItemEntity());
        mCustomAdapter.notifyDataSetChanged();
    }

    /**
     * 检查数据并回传
     */
    private void checkData() {
        if (mEntity == null) return;
        //todo 字段待替换
        //项目名称
        if (binding.etReleaseCargoProjectName.getText() != null) {
            mEntity.setProjectName(binding.etReleaseCargoProjectName.getText().toString());
        } else {
            mEntity.setProjectName("");
        }
        //项目描述
        if (binding.etReleaseCargoProjectDesc.getText() != null) {
            mEntity.setProjectDesc(binding.etReleaseCargoProjectDesc.getText().toString());
        } else {
            mEntity.setProjectDesc("");
        }
        //运输要求
        if (binding.etReleaseCargoTransportReq.getText() != null) {
            mEntity.setTransportReq(binding.etReleaseCargoTransportReq.getText().toString());
        } else {
            mEntity.setTransportReq("");
        }
        //甲方责任约定
        if (binding.etReleaseCargoPartyAAgreement.getText() != null) {
            mEntity.setPartyAAgreement(binding.etReleaseCargoPartyAAgreement.getText().toString());
        } else {
            mEntity.setPartyAAgreement("");
        }
        //乙方责任约定
        if (binding.etReleaseCargoPartyBAgreement.getText() != null) {
            mEntity.setPartyBAgreement(binding.etReleaseCargoPartyBAgreement.getText().toString());
        } else {
            mEntity.setPartyBAgreement("");
        }
        //违约约定
        if (binding.etReleaseCargoBreachOfContract.getText() != null) {
            mEntity.setBreachOfContract(binding.etReleaseCargoBreachOfContract.getText().toString());
        } else {
            mEntity.setBreachOfContract("");
        }
        //合同终止约定
        if (binding.etReleaseCargoTerminationAgreement.getText() != null) {
            mEntity.setTerminationAgreement(binding.etReleaseCargoTerminationAgreement.getText().toString());
        } else {
            mEntity.setTerminationAgreement("");
        }
        //判断自定义字段是否正确
        if (!loadFieldData()) {
            return;
        }
        Intent intent = new Intent();
        intent.putExtra(RouterKey.DATA, mEntity);
        setResult(RESULT_OK, intent);
        finish();
    }

    /**
     * 加载自定义字段
     */
    private boolean loadFieldData() {
        if (mCustomList != null && !mCustomList.isEmpty()) {
            Set<String> fieldName = new HashSet<>();
            //判断是否填写了自定义字段
            for (SingleItemEntity entity : mCustomList) {
                if (!fieldName.contains(entity.getLeftString())) {
                    fieldName.add(entity.getLeftString());
                } else {
                    MToast.showToast(this, "请检查新增字段名称是否有重复");
                    return false;
                }
                if (TextUtils.isEmpty(entity.getLeftString())) {
                    MToast.showToast(this, "请输入新增字段名称");
                    return false;
                }
                if (TextUtils.isEmpty(entity.getRightString())) {
                    MToast.showToast(this, String.format("请输入%s内容", entity.getLeftString()));
                    return false;
                }
            }
            //设置自定义字段
            mEntity.setCustomList(mCustomList);
        } else {
            mEntity.setCustomList(null);
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        AMapAddressEntity entity = AMapDialog.get(data);
        if (entity != null) {
            binding.tvReleaseCargoProjectAddress.setText(String.format("%s%s%s%s",
                    entity.getProvince(),
                    entity.getCity(),
                    entity.getDistrict(),
                    DefaultUtil.getString(entity.getSnippet())));
            //设置数据
            CargoPublishEntity.ProjectAddressEntity location = new CargoPublishEntity.ProjectAddressEntity();
            location.setProjectLatitude(entity.getLatitude());
            location.setProjectLongitude(entity.getLongitude());
            location.setProjectProvinceName(entity.getProvince());
            location.setProjectCityName(entity.getCity());
            location.setProjectDistrictName(entity.getDistrict());
            location.setProjectProvinceNo(entity.getProvinceNo());
            location.setProjectCityNo(entity.getCityNo());
            location.setProjectDistrictNo(entity.getDistrictNo());
            location.setAddress(entity.getSnippet());
            mEntity.setProjectAddress(location);
        }
    }
}
